from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action
from django.utils import timezone
import pytz
from django.conf import settings
from rest_framework.views import Response

from users.models import User
from payment.models import OrderInfo
from meiduo_admin.utils import get_time_zero
from goods.models import GoodsVisitCount
from meiduo_admin import const
from meiduo_admin.permissions import *


class IndexView(ViewSet):
    permission_classes = [IsAdminUser]

    @action(methods=["get"], detail=False)
    def total_count(self,request):
        """总用户"""
        count = User.objects.filter(is_staff=False).count()

        local_timezone = pytz.timezone(settings.TIME_ZONE)
        date = timezone.now().astimezone(tz=local_timezone).date()

        return Response({
            "count":count,
            "date":date
        })

    @action(methods=["get"],detail=False)
    def day_increment(self,request):
        """日增用户"""
        time_zero, date = get_time_zero()
        count = User.objects.filter(date_joined__gte=time_zero,is_staff=False).count()
        return Response({
            "count":count,
            "date":date
        })

    @action(methods=["get"],detail=False)
    def day_active(self,request):
        time_zero, date = get_time_zero()
        count = User.objects.filter(last_login__gte=time_zero,is_staff=False).count()
        return Response({
            "count":count,
            "date":date
        })

    @action(methods=["get"],detail=False)
    def day_orders(self,request):

        time_zero,date = get_time_zero()
        orders = OrderInfo.objects.filter(create_time__gte=time_zero)
        user_list = []
        for order in orders:
            user_list.append(order.user)
        count = len(set(user_list))
        return Response({
            "count":count,
            "date":date
        })

    @action(methods=["get"],detail=False)
    def month_increment(self,request):

        start_time,date = get_time_zero()
        end_time = timezone.now()
        data_list = []
        for i in range(const.user_show_day):
            count = User.objects.filter(date_joined__gte=start_time,date_joined__lt=end_time,is_staff=False).count()
            data_list.append(
                {
                    "count":count,
                    "date":end_time.date()
                })
            end_time = start_time
            start_time -= timezone.timedelta(days=1)

        return Response(data_list[::-1])

    @action(methods=["get"],detail=False)
    def goods_day_views(self,request):
        time_zero, date = get_time_zero()
        good_visits = GoodsVisitCount.objects.filter(create_time__gte=time_zero)
        data_list =[]
        for good_visit in good_visits:
            data_list.append({
                "category":good_visit.category.name,
                "count":good_visit.count
            })
        return Response(data_list)

